onload = () => {
    loadCSS("../css/common.css", "common");
    loadCSS("../css/fontello.css", "bootstrap5-icon");
    loadCSS("../css/bootstrap5.min.css", "bootstrap5");
    loadScript("../js/bootstrap5.bundle.min.js")
        .then(() => loadScript("../addon/autocomplete/autocomplete.js")).then(() => loadScript("../js/crud.js")).then(() => {
        let warehouseReceiveOperator = new Crud({
            module: "warehouseReceive",
            hasCheckbox: true,
            iterators: [{
                name: "warehouseReceive.category",
                iterator: [{"value": "3PL", "caption": "3PL"},
                    {"value": "GPS", "caption": "GPS"}]
            }, {
                name: "warehouseReceive.charge.type",
                iterator: [{"value": 1, "caption": "Handling"},
                    {"value": 2, "caption": "Storage"},
                    {"value": 3, "caption": "Freight Prepaid"},
                    {"value": 4, "caption": "Freight 3rd Party"},
                    {"value": 5, "caption": "Special Charges"},
                    {"value": 6, "caption": "Materials"},
                    {"value": 7, "caption": "Auto-calc Storage"},
                    {"value": 8, "caption": "Auto-calc Handling"}]
            }],
            extendAttribute: [{name: "warehouseReceiveId", type: "warehouseReceiveItem"},
                {name: "warehouseReceiveId", type: "warehouseReceiveCharge"},
                {name: "warehouseReceiveId", type: "warehouseReceiveFile"}
            ],
            extraInformation:
                [{caption: "Unit", field: "unit1"},
                    {caption: "Unit1 #", field: "unit1Number"},
                    {caption: "Unit2", field: "unit2"},
                    {caption: "Unit2 #", field: "unit2Number"},
                    {caption: "Total Weight", field: "totalWeight"},
                    {caption: "Total Volume", field: "totalVolume"},
                ],
            rowEvent: function (e, item, tr, outer) {
                outer.subTable["receiveLine"].load(item["warehouseReceiveId_warehouseReceiveItem"]);
                outer.subTable["receiveCharge"].load(item["warehouseReceiveId_warehouseReceiveCharge"]);
                outer.subTable["attaches"].load(item["warehouseReceiveId_warehouseReceiveFile"]);
                canvas.show();
            },
            rowBtn: ["edit", "delete", {
                "caption": "icon-icon-attach",
                "class": "btn btn-primary",
                hint: "Add attached file",
                "action": "modal",
                "param": "#uploadQuoteFile",
                "callback": (e) => {
                    e.preventDefault();
                    let form = document.getElementById("uploadQuoteFile").querySelector("form");
                    form.addEventListener("submit", async (evt) => {
                        evt.preventDefault();
                        const id = parseInt(e.target.closest("button").getAttribute("data-id"));
                        const fileInput = form.querySelector('#formFile');
                        const formData = new FormData();
                        formData.append("id", id);
                        formData.append('file', fileInput.files[0]);
                        ajax("/warehouse/receive/file", {method: "POST", body: formData, headers: {}}, data => {
                            showToast(`Upload successful: ${JSON.stringify(data.data)}`, "primary");
                            loadData();
                            let modalElement = document.getElementById("uploadQuoteFile");
                            const modal = bootstrap.Modal.getInstance(modalElement)
                                || new bootstrap.Modal(modalElement);
                            modal.hide();
                        }, error => showToast(error.message));
                    }, {once: true});
                }
            }, {
                "caption": "icon-icon-upload-cloud",
                hint: "Upload to CW",
                "class": "btn-warning", "callback": e => {
                    e.stopPropagation();
                    const id = parseInt(e.target.closest("button").getAttribute("data-id"));
                    ajax(`/warehouse/cw/push2?receiveId=${id}`, {}, (data) => showToast(`receive number: ${data.data}<br/> message: ${data.message}`, data.data && "primary"), (error) =>
                        showToast(error))
                }
            }],
            opsButton: ["delete", {
                "caption": "Import 3PL Receive",
                "class": "btn btn-primary",
                "callback": () => {
                    let receiveIds = prompt("Kindly input the transaction numbers you want to import, separated by commas.");
                    if (receiveIds) {
                        receiveIds.split(',').forEach(receiveId => {
                            ajax(`/3pl/receive?receiveId=${receiveId}`, {}, () => delayLoad.run(loadData, 200), (error) => showToast("Transaction ID:[" + receiveId + "] import error caused by:" + error));
                        });
                    }
                }
            }, {
                "caption": "Upload ",
                "class": "btn btn-primary",
                hint: "Add GPS file",
                "action": "modal",
                "param": "#uploadQuoteFile",
                "commit": (form, e) => {
                    const fileInput = form.querySelector('#formFile');
                    const formData = new FormData();
                    formData.append('file', fileInput.files[0]);
                    ajax("/gps/excel", {method: "POST", body: formData, headers: {}}, data => {
                        showToast(`Upload successful: ${JSON.stringify(data.data)}`, "primary");
                        loadData();
                        let modalElement = document.getElementById("uploadQuoteFile");
                        const modal = bootstrap.Modal.getInstance(modalElement)
                            || new bootstrap.Modal(modalElement);
                        modal.hide();
                    }, error => showToast(error.message));
                }
            }],
            search: [
                {"caption": "Ref#", "name": "reference", class: "col-3"},
                {"caption": "Transaction#", "name": "transactionId", class: "col-3"},
                {
                    caption: "Source",
                    name: "source",
                    type: "combo",
                    iterator: "blank_ALL_warehouseReceive.category",
                    class: "col-3"
                }
            ],
            listField: [{"caption": "ID", "field": "warehouseReceiveId"},
                {"caption": "Source", "field": "source"},
                {"caption": "Customer", "field": "customer"},
                {"caption": "Warehouse", "field": "warehouse"},
                {"caption": "Transaction #", "field": "transactionId"},
                {"caption": "Ref #", "field": "reference"},
                {"caption": "PO #", "field": "purchaseNumber"},
                {"caption": "Ship To", "field": "shipToCompanyName"}],
            editFields: [
                {caption: "Customer", "name": "customer", "placeHolder": "", class: "col-3"},
                {"name": "warehouse", "placeHolder": "", class: "col-3"},
                {"name": "transactionId", "placeHolder": "", class: "col-3"},
                {"name": "reference", "placeHolder": "", class: "col-3"},
                {"name": "purchaseNumber", "placeHolder": "", class: "col-3"},
                {"name": "shipToCompanyName", "placeHolder": "", class: "col-3"},
            ],
            subTable: [{
                name: "receiveLine",
                tableId: "warehouseReceiveLine",
                listField: [{"caption": "Sku", "field": "sku"},
                    {"caption": "Quantity", "field": "quantity"}],
            }, {
                name: "receiveCharge",
                tableId: "warehouseReceiveCharge",
                listField: [{"caption": "Type", "field": "chargeType", iterator: "warehouseReceive.charge.type"},
                    {"caption": "Charge Code", "field": "chargeCode"},
                    {"caption": "Label", "field": "label"},
                    {"caption": "Unit", "field": "Unit"},
                    {"caption": "No.", "field": "number"},
                    {"caption": "Price", "field": "price"}],
            }, {
                name: "attaches",
                tableId: "attaches",
                pk: "fileId",
                rowBtn: [{
                    caption: "icon-icon-search",
                    callback: e => {
                        window.open(contentPath + "/file/show?fileId=" + e.target.closest("button").dataset.id, "_blank")
                    }
                }, {
                    caption: "icon-icon-trash-empty",
                    callback: e => {
                        ajax(`/file/delete?fileId=${e.target.closest("button").dataset.id}`, {}, () => {
                            showToast("Delete file success");
                            loadData();
                            canvas.hide();
                        });
                    }
                }],
                listField: [{"caption": "name", "field": "name"},
                    {"caption": "Category", "field": "category"}],
            }]
        });
        warehouseReceiveOperator.init();

        function loadData() {
            warehouseReceiveOperator.loadData();
        }

        const canvas = new bootstrap.Offcanvas(document.getElementById('subtable'));
    }).catch((err) => console.error(err));
}
